//获取系统时间
var newDate = '';
getLangDate();
//值小于10时，在前面补0
function dateFilter(date){
    if(date < 10){return "0"+date;}
    return date;
}
function getLangDate(){
    var dateObj = new Date(); //表示当前系统时间的Date对象
    var year = dateObj.getFullYear(); //当前系统时间的完整年份值
    var month = dateObj.getMonth()+1; //当前系统时间的月份值
    var date = dateObj.getDate(); //当前系统时间的月份中的日
    var day = dateObj.getDay(); //当前系统时间中的星期值
    var weeks = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
    var week = weeks[day]; //根据星期值，从数组中获取对应的星期字符串
    var hour = dateObj.getHours(); //当前系统时间的小时值
    var minute = dateObj.getMinutes(); //当前系统时间的分钟值
    var second = dateObj.getSeconds(); //当前系统时间的秒钟值
    var timeValue = "" +((hour >= 12) ? (hour >= 18) ? "晚上" : "下午" : "上午" ); //当前时间属于上午、晚上还是下午
    newDate = dateFilter(year)+"年"+dateFilter(month)+"月"+dateFilter(date)+"日 "+" "+dateFilter(hour)+":"+dateFilter(minute)+":"+dateFilter(second);
    setTimeout("getLangDate()",1000);
}
layui.extend({
    baseConfig : "/js/pages/baseConfig"
})
layui.use(['table','form','element','layer','jquery','baseConfig','util'],function(){
    var baseConfig = layui.baseConfig,
    $ = layui.jquery;
    var table = layui.table;
    var form = layui.form;
    var util = layui.util;
    var userInfo = JSON.parse( window.sessionStorage.getItem( "userInfo"));
    var lastLoginTime = userInfo.lastLoginTime;

    if( userInfo){
        //时间加上换行，这样更好看
        $(".loginTime").html( lastLoginTime.split("日")[0] + "日</br>" + lastLoginTime.split("日")[1]);
    }
    //icon动画
    $(".panel a").hover(function(){
        $( this).find( ".layui-anim").addClass( "layui-anim-scaleSpring");
    },function(){
        $( this).find( ".layui-anim").removeClass( "layui-anim-scaleSpring");
    })
    $(".panel a").click(function(){
        parent.addTab( $(this));
    });

    var tableIns1;
    var tableIns2;
    var tableIns3;
    var recuPersoTable;
    var depanPersoListTable;


    getSystemParam( $, "rechargeRate", function( data){
        //获取税率，计算实际到账的金额
        var rate = parseFloat( data.split( "%")[0]);
        if( !rate){
            rate = 0;
        }
        tableIns1 = table.render({
            elem: '#rechargeList1',
            url : '/recharge/listByDay?moneyStatus=1,2,3',
            cellMinWidth : 95,
            text: { none: "Aucun résultat"},
            height : "full",
            id : "listTable1",
            cols : [[
                {field: 'dealTime', title: "Date", align:"center", templet : function( d) {
                        return baseConfig.formatDate( d.dealTime);
                    }},
                {field: 'merchantOrderAmount', title: "TOL", align:"center", totalRow: true, templet: function( d) {
                        return parseFloat( parseFloat( d.merchantOrderAmount) * ( 1 - rate/100 )).toFixed( 2) + " €";
                    }},
                {title: 'État', align:"center", templet : function ( d) {
                    //如果是今天的金额，不展示操作按钮
                    //修改为前后一天都不显示确认到帐按钮 2020-06-07
                    var dis = new Date( d.dealTime).getTime() - new Date().getTime();
                    dis = Math.abs( dis);
                    if( dis > 24*6060*1000) {
                        return "<a class=\"layui-btn layui-btn-xs\" lay-event=\"setMoneyStatusOne\">确认到账</a>";
                    }else{
                        return "/";
                    }
                }}
            ]],
            response : {
                statusCode: 200 //规定成功的状态码，默认：0
            },
            parseData : function( res){ //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "data": res.data //解析数据列表
                };
            }
        });

        tableIns2 = table.render({
            elem: '#rechargeList2',
            url : '/recharge/listByDay?moneyStatus=4',
            cellMinWidth : 95,
            text: { none: "Aucun résultat"},
            height : "full",
            id : "listTable2",
            cols : [[
                {field: 'dealTime', title: "Date", align:"center", templet : function( d) {
                        return baseConfig.formatDate( d.updateMoneyStatusOne);
                    }},
                {field: 'merchantOrderAmount', title: "TOL", align:"center", totalRow: true, templet: function( d) {
                        return parseFloat( d.merchantOrderAmount).toFixed( 2) + " €";
                    }},
                {title: 'État', align:"center", templet : function ( d) {
                        return "<a class=\"layui-btn layui-btn-xs\" lay-event=\"setMoneyStatusTwo\">安排转账</a>";
                    }}
            ]],
            response : {
                statusCode: 200 //规定成功的状态码，默认：0
            },
            parseData : function( res){ //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "data": res.data //解析数据列表
                };
            }
        });

        tableIns3 = table.render({
            elem: '#rechargeList3',
            url : '/recharge/listByDay?moneyStatus=5',
            cellMinWidth : 95,
            height : "full",
            text: { none: "Aucun résultat"},
            id : "listTable3",
            cols : [[
                {field: 'dealTime', title: "Date", align:"center", templet : function( d) {
                        return baseConfig.formatDate( d.updateMoneyStatusTwo);
                    }},
                {field: 'merchantOrderAmount', title: "TOL", align:"center", totalRow: true, templet: function( d) {
                        return parseFloat( d.merchantOrderAmount).toFixed( 2) + " €";
                    }},
                {title: 'État', align:"center", templet : function ( d) {
                        return "<a class=\"layui-btn layui-btn-xs\" lay-event=\"setMoneyStatusThree\">已安排</a>";
                    }}
            ]],
            response : {
                statusCode: 200 //规定成功的状态码，默认：0
            },
            parseData : function( res){ //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "data": res.data //解析数据列表
                };
            }
        });
        recuPersoTable = table.render({
            elem: '#recuPersoList',
            url : '/recuPerso/list?status=2',
            cellMinWidth : 95,
            height : "full",
            id : "recuPersoList",
            text: { none: "Aucun résultat"},
            cols : [[
                {field: 'date', title: "Date", align:"center", templet : function( d){
                        return baseConfig.formatDate( d.date);
                    }},
                {field: 'contrepartie', title: "Contrepartie", align:'center'},
                {field: 'jobNumber', title: "ID", align:'center'},
                {field: 'methodeName', title: "Méthode", align:'center', templet : function( d){
                    return "<div style=\"overflow:hidden;white-space:nowrap;text-overflow:ellipsis;\">" + d.methodeName + "</div>";
                }},
                {field: 'memo', title: "Remarqe", align:'center', templet : function( d){
                    return "<div style=\"overflow:hidden;white-space:nowrap;text-overflow:ellipsis;\">" + d.memo + "</div>";
                }},
                {field: 'montant', title: "Montant", align:'center', templet: function ( d) {
                        return (parseFloat( d.montant)).toFixed( 2) + " €";
                    }},
                {title: 'État', align:"center", templet : function ( d) {
                        return "<a class=\"layui-btn layui-btn-xs\" lay-event=\"setRecuPersoStatus\">Approuvé</a>";
                    }}
            ]],
            response : {
                statusCode: 200 //规定成功的状态码，默认：0
            },
            parseData : function( res){ //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "data": res.data //解析数据列表
                };
            }
        });
        depanPersoListTable = table.render({
            elem: '#depanPersoList',
            url : '/depanPerso/list?status=2',
            cellMinWidth : 95,
            height : "full",
            text: { none: "Aucun résultat"},
            id : "depanPersoListTable",
            cols : [[
                {field: 'date', title: "Date", align:"center", templet : function( d){
                        return baseConfig.formatDate( d.date);
                    }},
                {field: 'cooperativeName', title: "Contrepartie", align:'center', templet : function( d){
                    return "<div style=\"overflow:hidden;white-space:nowrap;text-overflow:ellipsis;\">" + d.cooperativeName + "</div>";
                }},
                {field: 'jobNumber', title: "ID", align:'center'},
                {field: 'methode', title: "Méthode", align:'center', templet : function( d){
                    return "<div style=\"overflow:hidden;white-space:nowrap;text-overflow:ellipsis;\">" + d.methode + "</div>";
                }},
                {field: 'memo', title: "Remarqe", align:'center', templet : function( d){
                    return "<div style=\"overflow:hidden;white-space:nowrap;text-overflow:ellipsis;\">" + d.memo + "</div>";
                }},
                {field: 'montant', title: "Montant", align:'center',templet : function( d){
                    return parseFloat( d.montant).toFixed(2)
                }},
                {title: 'État', align:"center", templet : function ( d) {
                        var str = "<a class=\"layui-btn layui-btn-xs\" lay-event=\"editDepanPerso\">修改</a>";
                        str += "<a class=\"layui-btn layui-btn-xs\" lay-event=\"setDepanPersoStatus\">Approuvé</a>";
                        return str;
                    }}
            ]],
            response : {
                statusCode: 200 //规定成功的状态码，默认：0
            },
            parseData : function( res){ //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "data": res.data //解析数据列表
                };
            }
        });
    });

    //非管理员需要隐藏 充值记录到帐状态
    if( baseConfig.checkPrivalege( baseConfig.INDEX_DATA)){
        $(".rechargeListDiv").show();
        $(".recuPersoListDiv").show();
        $(".depanPersoListDiv").show();
    }else{
        $(".rechargeListDiv").hide();
        $(".recuPersoListDiv").hide();
        $(".depanPersoListDiv").hide();
    }

    function setMoentStatus( i, dealTime, moneyStatus){
        $.post( "/recharge/setMoneyStatusByDay", { "day": dealTime, 'moneyStatus': moneyStatus},
            function( res){
                layer.close( i);
                if( res.code == 200){
                    top.layer.msg( "设置成功");
                    //刷新表格
                    tableIns1.reload();
                    tableIns2.reload();
                    tableIns3.reload();
                }else{
                    top.layer.msg( res.msg);
                }
            }
        );
    }
    function setRecuPersoStatus( i, data){
        $.post( "/recuPerso/addOrUpdate", { "id": data.id, "status": "1"},
            function( res){
                layer.close( i);
                if( res.code == 200){
                    top.layer.msg( "设置成功");
                    //刷新表格
                    recuPersoTable.reload();
                }else{
                    top.layer.msg( res.msg);
                }
            }
        );
    }
    function setDepanPersoStatus( i, data){
        $.post( "/depanPerso/addOrUpdate", { "id": data.id, "status": "1"},
            function( res){
                layer.close( i);
                if( res.code == 200){
                    top.layer.msg( "设置成功");
                    //刷新表格
                    depanPersoListTable.reload();
                }else{
                    top.layer.msg( res.msg);
                }
            }
        );
    }

    var maxHeight = $(window).height();
    $(".add_btn_depen").click(function(){
        var index = layui.layer.open({
            title : "添加",
            type : 2,
            area: [800 + 'px', (maxHeight < 600 ? maxHeight-10 : 600) + 'px'],
            shade: 0.4,
            btnAlign: 'r',
            id: "depanPerso", //设定一个id，防止重复弹出
            content : "/pages/depanPerso/formData.html",
            success : function(){
                var body = layui.layer.getChildFrame( 'body', index);
                body.find( "input[name=contrepartie]").val( "NUXUA").attr( "readonly", true);//标识是修改还是新增
                form.render();
                setTimeout( function(){
                    layui.layer.tips('点击此处返回数据列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500);
            }
        });
    });

    $(".add_btn_recu").click(function(){
        var index = layui.layer.open({
            title : "添加",
            type : 2,
            area: [600 + 'px', (maxHeight < 400 ? maxHeight-10 : 400) + 'px'],
            shade: 0.4,
            btnAlign: 'r',
            id: "recuPerso", //设定一个id，防止重复弹出
            content : "/pages/recuPerso/formData.html",
            success : function(){
                var body = layui.layer.getChildFrame( 'body', index);
                body.find( "input[name=contrepartie]").val( "NUXUA").attr( "readonly", true);//标识是修改还是新增
                form.render();
                setTimeout( function(){
                    layui.layer.tips('点击此处返回数据列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500);
            }
        });
    });

    //查询 账户总额信息
    $.get("/mooncardClient/getAccountTotal",function( res){
        if( res.code == 200){
            var total = res.data;
            getSystemParam( $, "mooncardBaseCount", function( data){
                var mooncardBaseCount = data;
                $("input[name=total_count]").val( (parseFloat( total) + ( mooncardBaseCount ? parseFloat( mooncardBaseCount) : 0.00)).toFixed(2));
            });

        }
    });
    //手动同步流水数据
    $("#sync_data_btn_mooncard").click(function(){
        var index = layer.open({ type: 3});
        $.post("/mooncardClient/syncData",{},function( res){
            if( res.code == 200){
                layer.close( index);
                top.layer.msg( "同步交易流水成功");
            }else{
                top.layer.close( index);
                top.layer.msg( "同步交易流水失败");
            }
        });
    });

    //不是管理要，隐藏上面那一排按钮
    if( !baseConfig.checkPrivalege( baseConfig.CONSUMER_LIST_ALL)){
        $( "#operation_tool").hide();
    }

    //列表操作
    table.on('tool(list)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'setMoneyStatusOne'){
            layer.confirm( "确定设置[" + data.dealTime + "]这天的充值记录到账状态？", function( i){
                setMoentStatus( i, data.dealTime, "4");
            });
        }else if(layEvent === 'setMoneyStatusTwo'){
            layer.confirm( "确定设置[" + data.dealTime + "]这天的充值记录到账状态？", function( i){
                setMoentStatus( i, data.dealTime, "5");
            });
        }else if(layEvent === 'setMoneyStatusThree'){
            layer.confirm( "确定设置[" + data.dealTime + "]这天的充值记录到账状态？", function( i){
                setMoentStatus( i, data.dealTime, "6");
            });
        }else if(layEvent === 'setRecuPersoStatus'){
            layer.confirm( "确定设置这笔充值记录为到帐状态？", function( i){
                setRecuPersoStatus( i, data);
            });
        }else if(layEvent === 'setDepanPersoStatus'){
            layer.confirm( "确定设置这笔消费记录为到帐状态？", function( i){
                setDepanPersoStatus( i, data);
            });
        }else if(layEvent === 'editDepanPerso'){
            var index = layui.layer.open({
                title : "编辑",
                type : 2,
                area: [800 + 'px', (maxHeight < 600 ? maxHeight-10 : 600) + 'px'],
                shade: 0.4,
                btnAlign: 'r',
                id: "depanPerso", //设定一个id，防止重复弹出
                content : "/pages/depanPerso/formData.html?cooperativeNumber=" + data.cooperativeNumber,
                success : function(){
                    var body = layui.layer.getChildFrame( 'body', index);
                    body.find( "#methodeId").val( data.methode);
                    body.find( "input[name=id]").val( data.id);//标识是修改还是新增
                    body.find( "#jobNumberId").val( data.jobNumber);
                    body.find( "input[name=memo]").val( data.memo);
                    body.find( "input[name=date]").val( baseConfig.formatDate( data.date));
                    body.find( "input[name=montant]").val( data.montant);
                    form.render();
                    setTimeout( function(){
                        layui.layer.tips('点击此处返回数据列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500);
                }
            });
        }
    });
})
